package thread.day2;

/**用同步方法解决线程安全问题
 *   把逻辑改造成线程同步的方法
 *
 * @author wx
 * @create 2019-11-28 15:51
 */
public class SynchronizedMethodDemo3 {
    public static void main(String[] args) {
        TicketsSell w = new TicketsSell();
        Thread t1 = new Thread(w);
        Thread t2 = new Thread(w);
        Thread t3 = new Thread(w);


        t1.setName("windows-1");
        t2.setName("windows-2");
        t3.setName("windows-3");
        t1.start();
        t2.start();
        t3.start();

    }

}

class TicketsSell implements  Runnable{


    int ticket = 100;
    @Override
    public void run() {
        while (true){
            int flag = sellTickets();
            //注意最后票是0张，如果flag == 1 其他线程进来会死循环
            if (flag == 0){
//                System.out.println("ticket null!");
                break;
            }
//            System.out.println(Thread.currentThread().getName());
        }
    }

    public synchronized int sellTickets(){
        if (ticket>0){
            System.out.println(Thread.currentThread().getName()+":"+ticket);
            ticket--;
        }
        return ticket;
    }
}